using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace CloudApiServer.Services;

/// <summary>
/// 目录下载服务
/// </summary>
public class CatalogDownService
{
    /// <summary>
    /// 目录下载相关接口 1301-1315 1320 1321
    /// </summary>
    /// <param name="fsiRequest"></param>
    /// <param name="ControllerName"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<OutputDownCatalog> DownCatalog(FsiRequestHeader<InputDownCatalog> fsiRequest, string ControllerName)
    {
        try
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.fixmedins_code;
            string ver = fsiRequest.Input.data.ver;
            string infno = fsiRequest.infno;
            if (string.IsNullOrEmpty(ver) || string.IsNullOrEmpty(infno))
            {
                throw new Exception("参数校验失败：传入的目录版本号|接口号为空为空，请检查入参！");
            }

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            string query = "select  * From fsi_downcatalog_filedetail where state=0 and infno = @infno and ver =@ver";
            var parameter = new List<MySqlParameter>
            {
                new MySqlParameter("@infno", infno),
                new MySqlParameter("@ver", ver),
            };
            DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
            if (dt.Rows.Count != 1)
            {
                throw new Exception($"获取目录数据版本失败！根据传入的接口号【{infno}】以及版本号【{ver}】查询到可下载的目录记录条数【{dt.Rows.Count}】，不符合预设的要求！");
            }
            
            var data = new OutputDownCatalog()
            {
                file_qury_no =dt.Rows[0]["file_qury_no"].ToString(),
                filename = dt.Rows[0]["filename"].ToString(),
                dld_endtime = dt.Rows[0]["dld_endtime"].ToString(),
                data_cnt = Convert.IsDBNull(dt.Rows[0]["data_cnt"]) ? 0 : int.Parse(dt.Rows[0]["data_cnt"].ToString())
            };
            return data;

        }
        catch (Exception ex)
        {
            LogHelper.Error($"[CatalogDownService.DownCatalog]目录下载发生异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
            throw;
        }
    }
}